﻿namespace AntdUI_HamburgerMenuTabs.Uc
{
    /// <summary>
    /// 汉堡包菜单 + 多标签页面
    /// </summary>
    public partial class HamburgerMenu : UserControl
    {
        public HamburgerMenu()
        {
            InitializeComponent();

            InitMenu();

            Menu = menu1;
        }

        public AntdUI.Menu? Menu;
        private AntdUI.Splitter? splitterMenu = null;

        /// <summary>
        /// 主菜单
        /// </summary>
        private List<Common.Models.MenuItem> _menus = [];

        private readonly HashSet<string> menuCodes = [];

        /// <summary>
        /// 创建菜单
        /// </summary>
        /// <param name="parent1"></param>
        /// <param name="parent2"></param>
        private void CreateMenu(Common.Models.MenuItem? parent1, AntdUI.MenuItem? parent2)
        {
            List<Common.Models.MenuItem> _menus;

            if (parent1 == null)
            {
                _menus = this._menus;
            }
            else
            {
                _menus = parent1.Sub;
            }

            foreach (Common.Models.MenuItem _item in _menus)
            {
                if (menuCodes.Contains(_item.Code))
                {
                    throw new Exception($"菜单唯一编码（{_item.Code}）重复！");
                }
                else
                {
                    menuCodes.Add(_item.Code);
                }

                AntdUI.MenuItem item = new(_item.Name)
                {
                    IconSvg = _item.IconSvg,
                    Tag = new Common.Models.MenuItemTag(_item.Code) { PageType = _item.PageType, Closeable = _item.Closeable, },
                };

                if (parent2 == null)
                {
                    menu1.Items.Add(item);
                }
                else
                {
                    parent2.Sub.Add(item);
                }

                if (_item.Sub.Count > 0) CreateMenu(_item, item);
            }
        }

        /// <summary>
        /// 设置菜单项
        /// </summary>
        /// <param name="menus"></param>
        public void SetMenu(List<Common.Models.MenuItem>? menus)
        {
            if (menus != null) _menus = menus;
            menu1.Items.Clear();
            menuCodes.Clear();
            CreateMenu(null, null);
            MenuItemCollapsedAll(null);
            SetMenuItemParent(null);
            SetMenuItemPath(null);
        }

        /// <summary>
        /// 设置菜单栏的父级 Splitter，用于控制菜单栏的宽度
        /// </summary>
        /// <param name="splitter"></param>
        public void SetSplitterMenu(AntdUI.Splitter splitter)
        {
            splitterMenu = splitter;
        }

        /// <summary>
        /// 初始化菜单
        /// </summary>
        private void InitMenu()
        {
            SetMenu(null);

            #region 菜单栏收缩/展开

            btnMenuCollapsed.Click += (s, e) =>
            {
                if (!menu1.Collapsed)
                {
                    MenuCollapse();
                    Properties.Settings.Default.MenuCollapsed = true;
                }
                else
                {
                    MenuExpand();
                    Properties.Settings.Default.MenuCollapsed = false;
                }
                Properties.Settings.Default.Save();
            };

            #endregion

            #region 菜单搜索输入框

            DateTime searchTextChangedTime = DateTime.Now;
            bool searchFinished = true;
            int searchDelayMs = 500;    // 延时搜索（毫秒）

            System.Windows.Forms.Timer timerMenuSearch = new() { Interval = 10 };

            timerMenuSearch.Tick += (s, e) =>
            {
                if ((DateTime.Now - searchTextChangedTime).TotalMilliseconds > searchDelayMs && !searchFinished)
                {
                    MenuSearch(null);
                    if (inputMenuSearch.Text == "") MenuItemCollapsedAll(null);
                    searchFinished = true;
                    timerMenuSearch.Stop();
                }
            };

            timerMenuSearch.Start();

            // 输入框文本变更时触发菜单搜索
            inputMenuSearch.TextChanged += (s, e) =>
            {
                searchTextChangedTime = DateTime.Now;
                searchFinished = false;
                timerMenuSearch.Start();
            };

            #endregion

            #region 右键菜单

            AntdUI.IContextMenuStripItem[] cMenu1 = [
                new AntdUI.ContextMenuStripItem("全部折叠", "")
                {
                    IconSvg = "MenuFoldOutlined",
                },
                new AntdUI.ContextMenuStripItem("全部展开", "")
                {
                    IconSvg = "MenuUnfoldOutlined",
                },
            ];

            menu1.MouseClick += (s, e) =>
            {
                if (e.Button == MouseButtons.Right)
                {
                    AntdUI.ContextMenuStrip.open(this, it =>
                    {
                        switch (it.Text)
                        {
                            case "全部折叠":
                                MenuItemCollapsedAll(null);
                                break;
                            case "全部展开":
                                MenuItemExpandAll(null);
                                break;
                        }
                    }, cMenu1);
                }
            };

            #endregion
        }

        /// <summary>
        /// 菜单栏收缩
        /// </summary>
        private void MenuCollapse()
        {
            MenuItemCollapsedAll(null);
            inputMenuSearch.Visible = false;
            btnMenuCollapsed.Dock = DockStyle.Fill;
            if (splitterMenu != null)
            {
                splitterMenu.SplitterDistance = (int)(70 * AntdUI.Config.Dpi);
                splitterMenu.IsSplitterFixed = true;
            }
        }

        /// <summary>
        /// 菜单栏展开
        /// </summary>
        private void MenuExpand()
        {
            btnMenuCollapsed.Dock = DockStyle.Left;
            inputMenuSearch.Visible = true;
            if (splitterMenu != null)
            {
                splitterMenu.SplitterDistance = (int)(260 * AntdUI.Config.Dpi);
                splitterMenu.IsSplitterFixed = false;
            }
        }

        /// <summary>
        /// 加载菜单折叠/展开状态
        /// </summary>
        public void LoadMenuCollapseStatus()
        {
            if (Properties.Settings.Default.MenuCollapsed)
            {
                MenuCollapse();
            }
            else
            {
                MenuExpand();
            }
        }

        /// <summary>
        /// 折叠所有菜单项
        /// </summary>
        /// <param name="parent"></param>
        public void MenuItemCollapsedAll(AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.Expand) item.Expand = false;
                if (item.Sub != null) MenuItemCollapsedAll(item);
            }
        }

        /// <summary>
        /// 展开所有菜单项
        /// </summary>
        /// <param name="parent"></param>
        private void MenuItemExpandAll(AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.CanExpand && !item.Expand) item.Expand = true;
                if (item.Sub != null) MenuItemExpandAll(item);
            }
        }

        /// <summary>
        /// 展开指定菜单项的所有上级菜单
        /// </summary>
        /// <param name="item"></param>
        private static void MenuItemExpandAllParent(AntdUI.MenuItem item)
        {
            if (item.Tag is Common.Models.MenuItemTag tag)
            {
                if (tag.Parent != null)
                {
                    if (tag.Parent.CanExpand && !tag.Parent.Expand)
                    {
                        tag.Parent.Expand = true;
                        // 选中上级菜单，当 Menu.Collapsed = true 时可以看到效果
                        tag.Parent.Select = true;
                    }
                    MenuItemExpandAllParent(tag.Parent);
                }
            }
        }

        /// <summary>
        /// MenuItem 选择模式：0=默认；1=自定义程序控制；
        /// </summary>
        public int menuSelectMode = 0;

        /// <summary>
        /// 选中指定菜单项
        /// </summary>
        /// <param name="path"></param>
        /// <param name="parent"></param>
        public void MenuItemSelectOne(string path, AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.Tag is Common.Models.MenuItemTag tag)
                {
                    if (tag.Path != null)
                    {
                        if (string.Equals(tag.Path, path, StringComparison.OrdinalIgnoreCase))
                        {
                            item.Select = true;
                            MenuItemExpandAllParent(item);
                        }
                        else
                        {
                            item.Select = false;
                        }
                    }
                }
                if (item.Sub != null) MenuItemSelectOne(path, item);
            }
        }

        /// <summary>
        /// 取消所有菜单项的选中状态
        /// </summary>
        /// <param name="parent"></param>
        private void MenuItemUnSelectAll(AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.Select)
                {
                    item.Select = false;
                }
                if (item.Sub != null) MenuItemUnSelectAll(item);
            }
        }

        /// <summary>
        /// 搜索菜单
        /// </summary>
        /// <param name="parent"></param>
        private void MenuSearch(AntdUI.MenuItem? parent)
        {
            string text = inputMenuSearch.Text;
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (text == "" && !item.Visible)
                {
                    item.Visible = true;
                }
                else
                {
                    if (item.Text!.IndexOf(text, StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        item.Visible = true;
                        if (!item.Expand) item.Expand = true;
                        MenuParentVisiable(item);
                    }
                    else
                    {
                        item.Visible = false;
                    }
                }
                if (item.Sub != null) MenuSearch(item);
            }
        }

        /// <summary>
        /// 把菜单项的所有父级菜单设置为可见
        /// </summary>
        /// <param name="item"></param>
        private static void MenuParentVisiable(AntdUI.MenuItem item)
        {
            if (item.Tag is Common.Models.MenuItemTag tag)
            {
                if (tag.Parent != null)
                {
                    if (!tag.Parent.Visible) tag.Parent.Visible = true;
                    if (!tag.Parent.Expand) tag.Parent.Expand = true;
                    MenuParentVisiable(tag.Parent);
                }
            }
        }

        /// <summary>
        /// 设置所有菜单项的父级
        /// </summary>
        /// <param name="parent"></param>
        private void SetMenuItemParent(AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.Tag is Common.Models.MenuItemTag tag)
                {
                    tag.Parent = parent;
                }
                if (item.Sub != null) SetMenuItemParent(item);
            }
        }

        /// <summary>
        /// 设置所有菜单项的路径
        /// </summary>
        /// <param name="parent"></param>
        private void SetMenuItemPath(AntdUI.MenuItem? parent)
        {
            AntdUI.MenuItemCollection items;
            if (parent == null) items = menu1.Items;
            else items = parent.Sub;
            foreach (AntdUI.MenuItem item in items)
            {
                if (item.Tag is Common.Models.MenuItemTag tag)
                {
                    if (parent == null)
                    {
                        if (tag.Path == null)
                        {
                            tag.Path = $"/{tag.Code}";
                            tag.Path2 = $"/{item.Text}";
                        }
                        else
                        {
                            tag.Path = $"/{tag.Code}";
                            tag.Path2 = $"/{tag.Path2}";
                        }
                    }
                    else
                    {
                        if (parent.Tag is Common.Models.MenuItemTag tag2)
                        {
                            if (tag.Path == null)
                            {
                                tag.Path = $"{tag2.Path}/{tag.Code}";
                                tag.Path2 = $"{tag2.Path2}/{item.Text}";
                            }
                            else
                            {
                                tag.Path = $"{tag2.Path}/{tag.Path}";
                                tag.Path = $"{tag2.Path2}/{tag.Path2}";
                            }
                        }
                    }
                }
                if (item.Sub != null) SetMenuItemPath(item);
            }
        }
    }
}